import React, {Component, PropTypes} from 'react'
import {Card, Tag, Button, Modal, Form, Input, message, Popconfirm, Col, Radio, Tabs} from 'antd'
import CheckRecord from '../../../../common/components/users/CheckRecord'
import Styles from './Index.less'
import {fetchPost} from '../../../../../utils/request'
import Identity from '../../../../common/components/users/Identity'
import Photos from '../../../../common/components/users/Photos'
import OCR from '../../../../common/components/users/OCR'
import Risk from '../../../common/detail/risk/Risk'
import BorrowRecord from '../../../../common/components/users/BorrowRecord'
import PhoneRemarkRecord from '../../../../common/components/users/PhoneRemarkRecord'
import FacePhoto from '../../../../common/components/users/Photos'
import KycAuthResult from '../../../common/detail/kyc/KycAuthResult'
import Info from '../../../common/detail/info/Info'
import TradeBankInfo from '../../../../common/components/users/TradeBankInfo'
import AppLists from '../../../../common/components/users/AppLists'
import BasicInfo from "../../../../common/components/users/BasicInfo";
import Profession from "../../../../common/components/users/Profession";
import Contact from "../../../../common/components/users/Contact";

const FormItem = Form.Item
const CheckableTag = Tag.CheckableTag
const TabPane = Tabs.TabPane
const RadioGroup = Radio.Group

class UncontrolledCheckableTag extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      activity: props.activity,
    }
  }

  componentWillReceiveProps(props) {
    if (props.activity != this.state.activity) {
      this.setState({
        activity: props.activity,
      })
    }
  }

  handleChange(activity) {
    this.setState({
      activity: !this.state.activity,
    })
    this.props.chooseTag(activity)
  };

  render() {
    return <CheckableTag checked={this.state.activity}
                         onChange={this.handleChange.bind(this)}>
      {this.props.tagName}
    </CheckableTag>
  }
}

class Detail extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: props.id,
      userId: props.userId,
      tradeNo: props.tradeNo,
      activeKey: props.activeKey,
      processNode: props.processNode,
      item: props.item,
      showDetail: true,
      stepType: props.stepType,
      visible: false,
      tagData: [],
      tagIDs: {},
      managerInfo: {
        finish: '',
        remain: '',
      },
      photoType: '',
      currentType: '',
      reuploadTypeList: null,
      extraStatus: props.extraStatus,
      photoReUploadTime: props.photoReUploadTime,
      photoReUploadAllow: props.photoReUploadAllow,
      canReedit: false,
      areaIds: [],
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData() {
    let self = this
    if (this.state.userId != null) {
      function getTags() {
        return new Promise((resolve, reject) => {
          fetchPost(`/audit/usertag/${self.state.userId}/1/query`).then((res) => {
            if (res.code === 0) {
              if (res.data.list != null) {
                resolve(res)
              } else {
                reject('')
              }
            } else {
              message.error(res.msg)
              reject(res)
            }
          })
        })
      }

      // function getManagerInfo() {
      //   return new Promise((resolve, reject) => {
      //     fetchPost(`/audit/usertag/${self.state.userId}/query`).then((res) => {
      //       if(res.code === 0) {
      //         resolve(res)
      //       } else {
      //         message.error(res.msg)
      //         reject(res)
      //       }
      //     })
      //   })
      // }

      Promise.all([getTags()]).then((res) => {
        let [resTags, resManagerInfo] = [res[0], res[1]]
        resTags.data.list.forEach((value, index) => {
          value.childList.forEach((val, ind) => {
            if (value.type === 13) {
              this.state.areaIds.push(val)
            } else {
              if (val.activity) {
                this.state.tagIDs[val.tagId] = true
              }
            }
          })
        })

        self.setState({
          tagData: resTags.data.list || [],
          managerInfo: {
            remain: '',
            finish: ''
          }
        }, () => {
          fetchPost(`/audit/usertag/${self.state.userId}/phone/query`, {}).then((res1) => {
            if (res1.code === 0) {
              res1.data.list.forEach((value1, index1) => {
                value1.childList.forEach((val1, ind1) => {
                  if (val1.activity) {
                    this.state.tagIDs[val1.tagId] = true
                  }
                })
              })

              let tmp = [];
              tmp = self.state.tagData;
              res1.data.list.map(tt => {
                tmp.push(tt);
              });

              self.setState({
                tagData: tmp || [],
                managerInfo: {
                  remain: '',
                  finish: '',
                },
              })
            } else {
              message.error(res.msg)
            }
          })
        })
      })
    }
  }

  componentWillReceiveProps(props) {
    if (this.state.id != props.id || this.state.userId != props.userId) {
      this.setState({
        id: props.id,
        activeKey: props.activeKey,
        userId: props.userId,
        tradeNo: props.tradeNo,
        stepType: props.stepType,
        item: props.item,
        extraStatus: props.extraStatus,
        photoReUploadTime: props.photoReUploadTime,
        photoReUploadAllow: props.photoReUploadAllow,
      }, () => {
        this.getData()
      })
    }
  }

  onChange(activeKey) {
    this.setState({activeKey})
  }

  changeOrder(type, id) {
    this.props.changeOrder(type, id)
  }

  operation(type) {
    this.setState({
      currentType: type
    }, () => {
      let reason = this.props.form.getFieldValue('checkReason')
      let self = this
      let tagIdList = []
      if (this.state.currentType == 'refuse' && !reason) {
        message.info("Please enter the reason");
        return false;
      }
      console.log(this.state.tagIDs, "2222222222222222222222222")
      for (let i in this.state.tagIDs) {
        tagIdList.push(i)
      }
      // 判断是否选择了城市区域
      let isChooseArea = false
      console.log(tagIdList, "11111111111111111111111111")
      this.state.areaIds.map(item => {
        tagIdList.map(itemTag => {
          if (itemTag == item.tagId) {
            isChooseArea = true
          }
        })
      })

      if (!isChooseArea) {
        message.info('Please choose the area')
        return false
      }
      this.props.form.validateFields((errors, values) => {
        if (!errors) {
          let operationParams = {
            auditNo: this.state.id,
            message: reason,
            userCode: this.state.userId,
            tradeNo: this.state.tradeNo,
            processNode: this.state.processNode,
            tagIdList,
            photoType: this.state.photoType
          }

          switch (type) {
            case 'pass':
              fetchPost('/audit/operate/pass', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  this.state.tagIDs = {}
                  self.changeOrder('pass', self.state.id)
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'refuse':
              fetchPost('/audit/operate/refuse', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'reedit':
              fetchPost('/audit/operate/reedit', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break
            default:
          }
        }
      })
    })
  }

  // 独立按钮使用
  operationV2(type) {
    this.setState({
      currentType: type
    }, () => {
      let reason = ''
      let self = this
      if (this.state.currentType == 'refuse') {
        reason = 'Photo audits exceed the number limit'
      }
      let operationParams = {
        auditNo: this.state.id,
        message: reason,
        userCode: this.state.userId,
        tradeNo: this.state.tradeNo,
        processNode: this.state.processNode,
        tagIdList: [],
        photoType: this.state.photoType
      }

      switch (type) {
        case 'pass':
          fetchPost('/audit/operate/pass', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              this.state.tagIDs = {}
              self.changeOrder('pass', self.state.id)
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'refuse':
          fetchPost('/audit/operate/refuse', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'reedit':
          fetchPost('/audit/operate/reedit', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break
        default:
      }
    })
  }

  clearReason() {
    this.props.form.setFieldsValue({
      checkReason: '',
    })
    this.setState({
      visible: false,
      tagIDs: {},
    }, () => {
      this.getData()
    })
  }

  extraContent() {
    return (
      <div>
      <span>
        <span className='ml10'> Loan ID: <span
          className='color-main'>{this.state.item.tradeNo || ''}</span></span>
        <span className='ml10 mr10'> Amount/Tenure:
          <span className='color-main'>
            {`${this.state.item.realCapital ||
            ''}₹/${this.state.item.productDuration || ''}`}
          </span>
        </span>
        {
          this.state.userId ? <Button type='primary'
                                      onClick={this.changeModal.bind(
                                        this)}>Operate</Button>
            : null
        }
      </span>
      </div>
    )
  }

  chooseTag(activity, id, name) {
    let self = this
    let form = this.props.form
    this.state.tagData.forEach((value, index) => {
      value.childList.forEach((val, ind) => {
        if (val.tagId == id) {
          val.activity = activity
        }
      })
    })

    this.setState({
      tagData: this.state.tagData || [],
    })

    if (activity) {
      this.state.tagIDs[id] = true
      if (form.getFieldValue('checkReason')) {
        form.setFieldsValue({
          checkReason: `${form.getFieldValue('checkReason') + name};`,
        })
      } else {
        form.setFieldsValue({
          checkReason: `${name};`,
        })
      }
    } else {
      let beforeReason = self.props.form.getFieldValue('checkReason')
      let currentReason = beforeReason.replace(new RegExp(`${name};`, 'g'), '')
      form.setFieldsValue({
        checkReason: currentReason,
      })
      delete this.state.tagIDs[id]
    }
  }

  changeParams(data) {
    if (data.photoType) {
      this.setState({
        photoType: data.photoType
      })
    }
  }

  photoReuploadCallback = (reuploadTypeList) => {
    this.setState({
      reuploadTypeList: reuploadTypeList,
    })
  };

  reuploadPhoto = () => {
    let self = this;
    console.log(this.state.reuploadTypeList, "------------------------------")
    if (this.state.reuploadTypeList != null) {
      fetchPost(`/user/photo/reupload`, {
        photoTypeList: this.state.reuploadTypeList,
        tradeNo: this.state.tradeNo,
      }).then(json => {
        if (json.code === 0) {
          self.clearReason();
          self.changeOrder('reupload', self.state.id);
          message.info('success')
        } else {
          message.error(json.msg)
        }
      })
    }
  }

  changeModal() {
    // fetchPost(`/audit/${this.state.item.userCode}/reedit/count`).then((json) => {
    //   if (json.code === 0) {
    //     this.setState({
    //       canReedit: json.data.canReedit,
    //       visible: !this.state.visible
    //     })
    //   } else {
    //     message.error(json.msg)
    //   }
    // })
    this.setState({
      visible: !this.state.visible
    })
  }

  showReeditButton() {
    if (this.state.canReedit) {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    } else {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' disabled className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    }
  }

  areaOnChange(e) {
    this.state.areaIds.map((item) => {
      delete this.state.tagIDs[item.tagId]
    })
    this.state.tagIDs[e.target.value] = true
  }

  tabChangeCallback = (key) => {
    console.log(key, 'choose tab call back')
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    return (
      <div>
        <Modal visible={this.state.visible}
               onOk={this.clearReason.bind(this)}
               onCancel={this.clearReason.bind(this)}
               footer={null}
               width="650"
        >
          <Form>
            <FormItem className={Styles.operationHeader}>
              <span className={Styles.title}>Order operation</span>
              {/*<Popconfirm placement='top' title='Confirm pass?'*/}
              {/*            onConfirm={() => {*/}
              {/*              this.operation('pass')*/}
              {/*            }}>*/}
              {/*  {(this.props.extraStatus != null && typeof (this.props.extraStatus) != 'undefined' && this.props.extraStatus == 1) ?*/}
              {/*    <Button type='primary' className='ml20' disabled>Pass</Button>*/}
              {/*    : (this.props.extraStatus != null && typeof (this.props.extraStatus) != 'undefined' && this.props.extraStatus == 9) ?*/}
              {/*      <Button type='primary' className='ml20'>Pass</Button>*/}
              {/*      : (this.state.reuploadTypeList == null ?*/}
              {/*        <Button type='primary' className='ml20'>Pass</Button>*/}
              {/*        : <Button type='primary' className='ml20' disabled>Pass</Button>)}*/}
              {/*</Popconfirm>*/}

              <Popconfirm placement='top' title='Confirm re-upload?'
                          onConfirm={this.reuploadPhoto}>
                {this.state.stepType == 'photoCheckReupload' ?
                  <Button type='primary' className='ml20'>Re-upload</Button>
                  :
                  (this.state.reuploadTypeList == null || (this.state.photoReUploadAllow != 1) ?
                    <Button type='primary' className='ml20' disabled>Re-upload</Button>
                    : <Button type='primary' className='ml20'>Re-upload</Button>)}
              </Popconfirm>

              <Popconfirm placement='top' title='Confirm refuse?'
                          onConfirm={() => {
                            this.operation('refuse')
                          }}>
                <Button type='primary' className='ml10'>Refuse</Button>
              </Popconfirm>
              {this.showReeditButton()}
            </FormItem>

            <FormItem>
              {getFieldDecorator('checkReason',
                {rules: [{message: 'Please enter the reason'}]})(
                <Input placeholder='Please enter the reason' className='mh150' type='textarea'/>,
              )}
            </FormItem>
          </Form>
          <Card noHovering title="User's area" className={Styles.partLeft}>
            <RadioGroup onChange={this.areaOnChange.bind(this)}>
              {
                this.state.tagData.map((cate) => {
                  if (cate.type === 13) {
                    return cate.childList.map((tag) => (
                      <Radio value={tag.tagId}>{tag.name}</Radio>))
                  }
                })
              }
            </RadioGroup>
          </Card>

          <Tabs onChange={this.tabChangeCallback} type="card">
            <TabPane tab="Reason label" key="1">
              <Card noHovering>
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type !== 13 && cate.type !== 14 && cate.type !== 15 && cate.type !== 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>
            <TabPane tab="Re-edit label" key="2">
              <Card noHovering>
                {
                  // console.log("123123123412341234123", this.state.tagData)
                }
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type === 14 || cate.type === 15 || cate.type === 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>
          </Tabs>
        </Modal>

        <div className={Styles.photoDetailWrap}>
          {/*<div className='mb10'>{this.extraContent()}</div>*/}
          <Card bodyStyle={{padding: 0}} bordered={false} noHovering={true}>
            <Tabs className={Styles.tabs} activeKey={this.state.activeKey}
                  onChange={(e) => this.onChange(e)}
                  tabBarExtraContent={this.extraContent()}>
              <TabPane tab='Photo Information' key='detail'>
                {
                  this.state.activeKey === 'detail' ?
                    <div>
                      <Col span={24}>
                        <Photos changeParams={(data) => {
                          this.changeParams(data)
                        }} userId={this.state.userId} tradeNo={this.state.tradeNo}
                                photoReUploadTime={this.state.photoReUploadTime}
                                photoReUploadAllow={this.state.photoReUploadAllow}
                                callbackParent={this.photoReuploadCallback}
                                stepType={this.state.stepType}
                        />
                        <Popconfirm placement='top' title='Confirm re-upload?'
                                    onConfirm={this.reuploadPhoto}>
                          {this.state.photoReUploadAllow != 1 ?
                            <Button type='primary' className='ml20' disabled>Re-upload</Button>
                            :
                            this.state.stepType == 'photoCheckReupload' ?
                              <Button type='primary' className='ml20'>Re-upload</Button>
                              :
                              (this.state.reuploadTypeList == null ?
                                <Button type='primary' className='ml20' disabled>Re-upload</Button>
                                : <Button type='primary' className='ml20'>Re-upload</Button>)}
                        </Popconfirm>

                        <Popconfirm placement='top' title='Confirm refuse?'
                                    onConfirm={() => {
                                      this.operationV2('refuse')
                                    }}>
                          {this.state.photoReUploadAllow == 1 ? null :
                            <Button type='primary' className='ml10'>Refuse</Button>}
                        </Popconfirm>
                      </Col>
                      <Col span={24}>
                        <Tabs onChange={this.callback} type="line">
                          <TabPane tab="BASIC" key="1">
                            <BasicInfo userId={this.state.userId} tradeNo={this.state.tradeNo} stepType={this.state.stepType}/>
                          </TabPane>
                          <TabPane tab="WORKING" key="2">
                            <Profession orderId={this.state.id} userId={this.state.tradeNo}/>
                          </TabPane>
                          {
                            this.state.processNode == '1' ? null
                              :
                              <TabPane tab="CONTACT" key="3">
                                <Contact id={this.state.id} userId={this.state.tradeNo}/>
                              </TabPane>
                          }
                        </Tabs>
                      </Col>
                      <Col span={24}>
                        <TradeBankInfo userId={this.state.userId} tradeNo={this.state.tradeNo}/>
                      </Col>
                      {/*<Col span={10}>*/}
                      {/*  <Identity userId={this.state.userId} tradeNo={this.state.tradeNo}/>*/}
                      {/*  /!*<OCR userId={this.state.userId} tradeNo={this.state.tradeNo} stepType={this.state.stepType}/>*!/*/}
                      {/*</Col>*/}
                    </div>
                    : <span/>
                }
              </TabPane>
              {/*<TabPane tab='Basic Information' key='info'>*/}
              {/*  {*/}
              {/*    this.state.activeKey === 'info'*/}
              {/*      ? <div className={Styles.tabsWrapper}>*/}
              {/*        <Col span={12}>*/}
              {/*          <Risk processNode={this.state.processNode} id={this.state.item} userId={this.state.tradeNo}/>*/}
              {/*          /!*<FacePhoto userId={this.state.userId} tradeNo={this.state.item.tradeNo}*/}
              {/*           stepType={this.state.stepType}/>*!/*/}
              {/*          /!*<OCR userId={this.state.userId} tradeNo={this.state.item.tradeNo}*/}
              {/*           stepType={this.state.stepType}/>*!/*/}
              {/*          <KycAuthResult userId={this.state.userId} tradeNo={this.state.item.tradeNo}*/}
              {/*                         stepType={this.state.stepType}/>*/}
              {/*          <TradeBankInfo userId={this.state.userId} tradeNo={this.state.tradeNo}/>*/}
              {/*        </Col>*/}
              {/*        <Col span={12}>*/}
              {/*          <Card title='' bodyStyle={{padding: '5px'}} noHovering>*/}
              {/*            <Contacts userId={this.state.tradeNo} id={this.state.id} showCategory={['2', '3']}/>*/}
              {/*            <AppLists userId={this.state.tradeNo}/>*/}
              {/*            /!*关于userId和tradeNo，写乱了，坑*!/*/}
              {/*          </Card>*/}
              {/*        </Col>*/}
              {/*      </div>*/}
              {/*      : <span></span>*/}
              {/*  }*/}
              {/*</TabPane>*/}
              <TabPane tab='Application History' key='records'>
                {
                  this.state.activeKey === 'records'
                    ? <div className={Styles.tabsWrapper}>
                      <BorrowRecord userId={this.state.tradeNo}/>
                      <PhoneRemarkRecord userId={this.state.tradeNo}/>
                      <CheckRecord userId={this.state.userId} tradeNo={this.state.tradeNo}/>
                    </div>
                    : <span/>
                }
              </TabPane>
            </Tabs>

            {/*<Col span={24}>*/}
            {/*  <CheckRecord userId={this.state.userId} tradeNo={this.state.tradeNo}/>*/}
            {/*</Col>*/}
          </Card>

        </div>
      </div>
    )
  }
}

Detail = Form.create()(Detail)

export default Detail
